const scripts = ['../assets/sortable.min.js'];
const getString = $utils.string.getString;

$('.page-content-area').ace_ajax('loadScripts', scripts, function () {
  $(document).ready(() => {
    (async () => {
      const store = {
        destinationsWithStrategies: [],
        destinationsWithNotes: [],
        destinationsWithHotDestinations: [],
        destinationsWithRecommendDestinations: []
      };
      const Sortable = window.Sortable;

      const $keywordForHot = $('#keywordForHot');
      const $keywordForSelection = $('#keywordForSelection');
      const $keywordForHotDestinations = $('#keywordForHotDestinations');
      const $keywordForRecommendDestinations = $('#keywordForRecommendDestinations');
      const $destinationsForHot = $('#destinationsForHot');
      const $destinationsForSelection = $('#destinationsForSelection');
      const $destinationsForHotDestinations = $('#destinationsForHotDestinations');
      const $destinationsForRecommendDestinations = $('#destinationsForRecommendDestinations');
      const $btnSaveForHot = $('#btnSaveForHot');
      const $btnSaveForSelection = $('#btnSaveForSelection');
      const $btnSaveForHotDestinations = $('#btnSaveForHotDestinations');
      const $btnSaveForRecommendDestinations = $('#btnSaveForRecommendDestinations');
      const $selectedDestinationsForHot = $('#selectedDestinationsForHot');
      const $selectedDestinationsForSelection = $('#selectedDestinationsForSelection');
      const $selectedDestinationsForHotDestinations = $('#selectedDestinationsForHotDestinations');
      const $selectedDestinationsForRecommendDestinations = $('#selectedDestinationsForRecommendDestinations');

      /**
       * 查询目的地列表数据
       */
      const queryDestinationList = function (clue) {
        return new Promise((resolve, reject) => {
          const url = $utils.ajax.setUrl('sysStrategy/getAllStrategyDestinationList');
          const requestData = {
            itemType: (() => {
              switch (clue) {
                case 'hot': return '1';
                case 'selection': return '2';
                case 'hotDestinations': return '3';
                case 'recommendDestinations': return '4';
                default: return '';
              }
            })()
          }
          axios.post(url, requestData).then(data => {
            if (data.code === '10000') {
              resolve(data);
            } else {
              reject(data);
            }
          }).catch(e => {
            reject(e);
          })
        });
      };

      /**
       * 设置攻略目的地排序接口
       * 参数 ：destinationIds, itemType（1=攻略目的地搜索，2=精选游记目的地，3=热门目的地，4=推荐旅行攻略）
       */
      const setStrategyDestinationSort = function ({ destinationIds = '', itemType = '' }) {
        return new Promise((resolve, reject) => {
          const url = $utils.ajax.setUrl('sysStrategy/setStrategyDestinationSort');
          const requestData = {
            destinationIds,
            itemType
          };
          axios.post(url, requestData).then(data => {
            if (data.code === '10000') {
              resolve(data);
            } else {
              reject(data);
            }
          }).catch(e => {
            reject(e);
          });
        });
      };

      /**
       * 查询目前已经设置了排序的目的地列表
       * 攻略首页顶部热搜目的地和精选游记列表处目的地接口
       * destinationType: 1攻略搜索，1精选游记（城市）列表，3=热门目的地，4=推荐旅行攻略
       */
      const getStrategyDestinationList = function ({ destinationType = '1' }) {
        return new Promise((resolve, reject) => {
          const url = $utils.ajax.setUrl('sysStrategy/getStrategyDestinationList');
          const requestData = {
            itemType: destinationType
          };
          axios.post(url, requestData).then(data => {
            if (data.code === '10000') {
              resolve(data);
            } else {
              reject(data);
            }
          }).catch(e => {
            reject(e);
          });
        });
      };

      /**
       * 填充目的地选项列表
       * @param clue：'hot'热搜目的地、'selection'精选目的地，'hotDestinations'热门目的地，'recommendDestinations'推荐旅行攻略
       * @returns {Promise<any>}
       */
      const fillDestinations = function (clue) {
        // const storeKeyName = 'destinationsWith' + (clue === 'hot' ? 'Strategies' : 'Notes');
        const storeKeyName = 'destinationsWith' + (() => {
          console.log(clue);
          switch (clue) {
            case 'hot': return 'Strategies';
            case 'selection': return 'Notes';
            case 'hotDestinations': return 'HotDestinations';
            case 'recommendDestinations': return 'RecommendDestinations';
            default: return '';
          }
        })();
        return new Promise(async (resolve, reject) => {
          try {
            if (store[storeKeyName].length === 0) {
              const data = await queryDestinationList(clue);
              store[storeKeyName] = (data.body || []).map(item => {
                return {
                  id: getString(item.DESTINATION_ID),
                  name: getString(item.DESTINATION_NAME)
                };
              });
            }
            let $keyword
            let $destinations
            if (clue === 'hot') {
              $keyword = $keywordForHot;
              $destinations = $destinationsForHot;
            } else if (clue === 'selection') {
              $keyword = $keywordForSelection;
              $destinations = $destinationsForSelection;
            } else if (clue === 'hotDestinations') {
              $keyword = $keywordForHotDestinations;
              $destinations = $destinationsForHotDestinations;
            } else if (clue === 'recommendDestinations') {
              $keyword = $keywordForRecommendDestinations;
              $destinations = $destinationsForRecommendDestinations;
            }
            const keyword = getString($keyword.val());
            const $selectedItemsWrapper = clue === 'hot' ? $selectedDestinationsForHot : $selectedDestinationsForSelection;
            const $selectedItems = $selectedItemsWrapper.find('.item');
            const selectedItems = (() => {
              const arr = [];
              $selectedItems.each((idx, elem) => {
                const id = getString($(elem).data('id'));
                arr.push(id);
              });
              return arr;
            })();
            $destinations.html(
              store[storeKeyName].filter(
                item => {
                  if (item.name.indexOf(keyword) === -1) {
                    // 与关键词不匹配的不显示在左侧栏
                    return false;
                  }
                  // 右侧栏已选的目的地不在左侧栏显示
                  if (selectedItems.indexOf(getString(item.id)) !== -1) {
                    return false;
                  }
                  return true;
                }
              ).map(
                item => `<li data-id="${item.id}" class="item"><span class="label">${item.name}</span></li>`
              ).join('')
            );
            resolve();
          } catch (e) {
            console.log(e);
            reject(e);
          }
        });
      };

      const getDestinationIds = function (clue) {
        let $destinations
        switch (clue) {
          case 'hot':
            $destinations = $selectedDestinationsForHot;
            break;
          case 'selection':
            $destinations = $selectedDestinationsForSelection;
            break;
          case 'hotDestinations':
            $destinations = $selectedDestinationsForHotDestinations;
            break;
          case 'recommendDestinations':
            $destinations = $selectedDestinationsForRecommendDestinations;
            break;
          default:
            break;
        }
        const arr = [];
        $destinations.find('.item').each((idx, elem) => {
          const $this = $(elem);
          const destinationId = $this.data('id');
          arr.push(destinationId);
        });
        return arr.join(',');
      }

      function generateHtmlForSelectedDestinations (list) {
        let html = '';
        list.forEach(item => {
          html += `
            <li data-id="${item.id}" class="item">
              <span class="label">${item.name}</span>
              <span class="btn-remove">移除</span>
            </li>
          `;
        });
        return html;
      }

      try {
        const dataForHot = await getStrategyDestinationList({ destinationType: '1' });
        const dataForSelection = await getStrategyDestinationList({ destinationType: '2' });
        const dataForHotDestinations = await getStrategyDestinationList({ destinationType: '3' });
        const dataForRecommendDestinations = await getStrategyDestinationList({ destinationType: '4' });
        const listForHot = dataForHot.body || [];
        const listForSelection = dataForSelection.body || [];
        const listForHotDestinations = dataForHotDestinations.body || [];
        const listForRecommendDestinations = dataForRecommendDestinations.body || [];
        $selectedDestinationsForHot.html(generateHtmlForSelectedDestinations(listForHot.map(item => {
          return {
            id: getString(item.DESTINATION_ID),
            name: getString(item.DESTINATION_NAME)
          };
        })));
        $selectedDestinationsForSelection.html(generateHtmlForSelectedDestinations(listForSelection.map(item => {
          return {
            id: getString(item.DESTINATION_ID),
            name: getString(item.DESTINATION_NAME)
          };
        })));
        $selectedDestinationsForHotDestinations.html(generateHtmlForSelectedDestinations(listForHotDestinations.map(item => {
          return {
            id: getString(item.DESTINATION_ID),
            name: getString(item.DESTINATION_NAME)
          };
        })));
        $selectedDestinationsForRecommendDestinations.html(generateHtmlForSelectedDestinations(listForRecommendDestinations.map(item => {
          return {
            id: getString(item.DESTINATION_ID),
            name: getString(item.DESTINATION_NAME)
          };
        })));
      } catch (e) {
        console.log(e);
        bootbox.alert('查询已排序目的地列表失败！');
      }

      try {
        await fillDestinations('hot');
        await fillDestinations('selection');
        await fillDestinations('hotDestinations');
        await fillDestinations('recommendDestinations');
      } catch (e) {
        console.log(e);
        bootbox.alert('填充目的地列表失败！');
      }

      $keywordForHot.on('input', async function (e) {
        const $this = $(this);
        const newVal = $this.val().replace(/\s/g, '');
        $this.val(newVal);
        await fillDestinations('hot');
      });

      $keywordForSelection.on('input', async function (e) {
        const $this = $(this);
        const newVal = $this.val().replace(/\s/g, '');
        $this.val(newVal);
        await fillDestinations('selection');
      });

      $keywordForHotDestinations.on('input', async function (e) {
        const $this = $(this);
        const newVal = $this.val().replace(/\s/g, '');
        $this.val(newVal);
        await fillDestinations('hotDestinations');
      });

      $keywordForRecommendDestinations.on('input', async function (e) {
        const $this = $(this);
        const newVal = $this.val().replace(/\s/g, '');
        $this.val(newVal);
        await fillDestinations('recommendDestinations');
      });

      $btnSaveForHot.click(async () => {
        const destinationIds = getDestinationIds('hot');
        if (destinationIds.length === 0) {
          bootbox.alert('请先添加目的地到右侧！');
          return;
        }
        const data = await setStrategyDestinationSort({
          destinationIds,
          itemType: '1'
        });
        if (data.code === '10000') {
          bootbox.alert('保存成功！');
        }
      });

      $btnSaveForSelection.click(async () => {
        const destinationIds = getDestinationIds('selection');
        if (destinationIds.length === 0) {
          bootbox.alert('请先添加目的地到右侧！');
          return;
        }
        const data = await setStrategyDestinationSort({
          destinationIds,
          itemType: '2'
        });
        if (data.code === '10000') {
          bootbox.alert('保存成功！');
        }
      });

      $btnSaveForHotDestinations.click(async () => {
        const destinationIds = getDestinationIds('hotDestinations');
        if (destinationIds.length === 0) {
          bootbox.alert('请先添加目的地到右侧！');
          return;
        }
        const data = await setStrategyDestinationSort({
          destinationIds,
          itemType: '3'
        });
        if (data.code === '10000') {
          bootbox.alert('保存成功！');
        }
      });

      $btnSaveForRecommendDestinations.click(async () => {
        const destinationIds = getDestinationIds('recommendDestinations');
        if (destinationIds.length === 0) {
          bootbox.alert('请先添加目的地到右侧！');
          return;
        }
        const data = await setStrategyDestinationSort({
          destinationIds,
          itemType: '4'
        });
        if (data.code === '10000') {
          bootbox.alert('保存成功！');
        }
      });

      Sortable.create(document.getElementById('selectedDestinationsForHot'));

      Sortable.create(document.getElementById('selectedDestinationsForSelection'));

      Sortable.create(document.getElementById('selectedDestinationsForHotDestinations'));

      Sortable.create(document.getElementById('selectedDestinationsForRecommendDestinations'));

      $destinationsForHot.on('click', '.item', function (e) {
        const $item = $(this);
        const id = $item.data('id');
        const name = $item.find('.label').text();
        $item.remove();
        $selectedDestinationsForHot.append(`
          <li data-id="${id}" class="item">
            <span class="label">${name}</span>
            <span class="btn-remove">移除</span>
          </li>
        `);
      });

      $destinationsForSelection.on('click', '.item', function (e) {
        const $item = $(this);
        const id = $item.data('id');
        const name = $item.find('.label').text();
        $item.remove();
        $selectedDestinationsForSelection.append(`
          <li data-id="${id}" class="item">
            <span class="label">${name}</span>
            <span class="btn-remove">移除</span>
          </li>
        `);
      });

      $destinationsForHotDestinations.on('click', '.item', function (e) {
        const $item = $(this);
        const id = $item.data('id');
        const name = $item.find('.label').text();
        $item.remove();
        $selectedDestinationsForHotDestinations.append(`
          <li data-id="${id}" class="item">
            <span class="label">${name}</span>
            <span class="btn-remove">移除</span>
          </li>
        `);
      });

      $destinationsForRecommendDestinations.on('click', '.item', function (e) {
        const $item = $(this);
        const id = $item.data('id');
        const name = $item.find('.label').text();
        $item.remove();
        $selectedDestinationsForRecommendDestinations.append(`
          <li data-id="${id}" class="item">
            <span class="label">${name}</span>
            <span class="btn-remove">移除</span>
          </li>
        `);
      });

      $selectedDestinationsForHot.on('click', '.btn-remove', function (e) {
        const $item = $(this).parents('.item');
        const destinationId = $item.data('id');
        const destinationName = $item.find('.label').text();
        const keyword = $keywordForHot.val();
        $item.remove();
        // 如果移除的项含有搜索关键词，则在左侧源中显示
        if (destinationName.indexOf(keyword) !== -1) {
          $destinationsForHot.append(`
            <li data-id="${destinationId}" class="item">
              <span class="label">${destinationName}</span>
            </li>
          `);
        }
      });

      $selectedDestinationsForSelection.on('click', '.btn-remove', function (e) {
        const $item = $(this).parents('.item');
        const destinationId = $item.data('id');
        const destinationName = $item.find('.label').text();
        const keyword = $keywordForSelection.val();
        $item.remove();
        // 如果移除的项含有搜索关键词，则在左侧源中显示
        if (destinationName.indexOf(keyword) !== -1) {
          $destinationsForSelection.append(`
            <li data-id="${destinationId}" class="item">
              <span class="label">${destinationName}</span>
            </li>
          `);
        }
      });

      $selectedDestinationsForHotDestinations.on('click', '.btn-remove', function (e) {
        const $item = $(this).parents('.item');
        const destinationId = $item.data('id');
        const destinationName = $item.find('.label').text();
        const keyword = $keywordForHotDestinations.val();
        $item.remove();
        // 如果移除的项含有搜索关键词，则在左侧源中显示
        if (destinationName.indexOf(keyword) !== -1) {
          $destinationsForHotDestinations.append(`
            <li data-id="${destinationId}" class="item">
              <span class="label">${destinationName}</span>
            </li>
          `);
        }
      });

      $selectedDestinationsForRecommendDestinations.on('click', '.btn-remove', function (e) {
        const $item = $(this).parents('.item');
        const destinationId = $item.data('id');
        const destinationName = $item.find('.label').text();
        const keyword = $keywordForRecommendDestinations.val();
        $item.remove();
        // 如果移除的项含有搜索关键词，则在左侧源中显示
        if (destinationName.indexOf(keyword) !== -1) {
          $destinationsForRecommendDestinations.append(`
            <li data-id="${destinationId}" class="item">
              <span class="label">${destinationName}</span>
            </li>
          `);
        }
      });
    })();
  });
});
